#!/bin/bash

# API测试脚本
# 用于快速验证DSL ORM生成的RESTful API功能

BASE_URL="http://localhost:3001"
USER_ID=""
ORDER_ID=""

echo "🧪 开始API功能测试"
echo "==================="

# 1. 健康检查
echo "\n1️⃣ 健康检查"
echo "GET $BASE_URL/health"
curl -s "$BASE_URL/health" | jq .

# 2. 创建用户
echo "\n2️⃣ 创建用户"
echo "POST $BASE_URL/api/user"
USER_RESPONSE=$(curl -s -X POST "$BASE_URL/api/user" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "name": "Test User",
    "age": 25
  }')

echo "$USER_RESPONSE" | jq .
USER_ID=$(echo "$USER_RESPONSE" | jq -r '.data.id // .id // empty')
echo "创建的用户ID: $USER_ID"

# 3. 获取用户列表
echo "\n3️⃣ 获取用户列表"
echo "GET $BASE_URL/api/user"
curl -s "$BASE_URL/api/user" | jq .

# 4. 获取单个用户
if [ ! -z "$USER_ID" ]; then
  echo "\n4️⃣ 获取单个用户"
  echo "GET $BASE_URL/api/user/$USER_ID"
  curl -s "$BASE_URL/api/user/$USER_ID" | jq .
else
  echo "\n4️⃣ 跳过获取单个用户（用户ID为空）"
fi

# 5. 更新用户
if [ ! -z "$USER_ID" ]; then
  echo "\n5️⃣ 更新用户"
  echo "PUT $BASE_URL/api/user/$USER_ID"
  curl -s -X PUT "$BASE_URL/api/user/$USER_ID" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Updated Test User",
      "age": 26
    }' | jq .
else
  echo "\n5️⃣ 跳过更新用户（用户ID为空）"
fi

# 6. 创建订单
if [ ! -z "$USER_ID" ]; then
  echo "\n6️⃣ 创建订单"
  echo "POST $BASE_URL/api/order"
  ORDER_RESPONSE=$(curl -s -X POST "$BASE_URL/api/order" \
    -H "Content-Type: application/json" \
    -d "{
      \"orderNumber\": \"ORD-$(date +%s)\",
      \"amount\": 99.99,
      \"userId\": \"$USER_ID\"
    }")
  
  echo "$ORDER_RESPONSE" | jq .
  ORDER_ID=$(echo "$ORDER_RESPONSE" | jq -r '.data.id // .id // empty')
  echo "创建的订单ID: $ORDER_ID"
else
  echo "\n6️⃣ 跳过创建订单（用户ID为空）"
fi

# 7. 获取订单列表
echo "\n7️⃣ 获取订单列表"
echo "GET $BASE_URL/api/order"
curl -s "$BASE_URL/api/order" | jq .

# 8. 获取单个订单
if [ ! -z "$ORDER_ID" ]; then
  echo "\n8️⃣ 获取单个订单"
  echo "GET $BASE_URL/api/order/$ORDER_ID"
  curl -s "$BASE_URL/api/order/$ORDER_ID" | jq .
else
  echo "\n8️⃣ 跳过获取单个订单（订单ID为空）"
fi

# 9. 更新订单状态
if [ ! -z "$ORDER_ID" ]; then
  echo "\n9️⃣ 更新订单状态"
  echo "PUT $BASE_URL/api/order/$ORDER_ID"
  curl -s -X PUT "$BASE_URL/api/order/$ORDER_ID" \
    -H "Content-Type: application/json" \
    -d '{
      "status": "confirmed"
    }' | jq .
else
  echo "\n9️⃣ 跳过更新订单（订单ID为空）"
fi

# 10. 测试查询参数
echo "\n🔟 测试查询参数"
echo "GET $BASE_URL/api/user?limit=5&offset=0"
curl -s "$BASE_URL/api/user?limit=5&offset=0" | jq .

echo "\n✅ API测试完成！"
echo "\n💡 提示："
echo "  - 如果看到错误，请检查服务器是否正在运行"
echo "  - 使用 'npm run start:server' 启动服务器"
echo "  - 访问 http://localhost:3001/health 检查服务器状态"
echo "  - 访问 http://localhost:3001/api 查看API文档"